package com.mall.thread.demo2;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;

public class LockTest {
    private Lock lock = new ReentrantLock(); // ReentrantLock是Lock的子类

    /**
     * 就是tryLock()这个方法跟Lock()是有区别的，
     * Lock在获取锁的时候，如果拿不到锁，就一直处于等待状态，直到拿到锁，
     * 但是tryLock()却不是这样的，tryLock是有一个Boolean的返回值的，
     * 如果没有拿到锁，直接返回false，停止等待，它不会像Lock()那样去一直等待获取锁
     * *  tryLock()是可以进行设置等待的相应时间的。
     * @param thread
     * @throws InterruptedException
     */
    private void method(Thread thread) throws InterruptedException {
        //lock.lock(); // 获取锁对象
        if(lock.tryLock( 5,TimeUnit.SECONDS)){
            try {
                System.out.println("线程名："+thread.getName() + "获得了锁");
                 Thread.sleep(3000);
            }catch(Exception e){
                e.printStackTrace();
            } finally {
                System.out.println("线程名："+thread.getName() + "释放了锁");
                lock.unlock(); // 释放锁对象
            }
        }
    }

    public static void main(String[] args) {
        LockTest lockTest = new LockTest();
        // 线程1
        Thread t1 = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                lockTest.method(Thread.currentThread());
            }
        }, "t1");

        // 线程2
        Thread t2 = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                lockTest.method(Thread.currentThread());
            }
        }, "t2");

        t1.start();
        t2.start();
    }

}
